<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table{
      border-collapse: collapse;
      width:50%;
    }
    td, th{
      font-size: 20px;
      text-align: center;
      border: 1px solid #000;
    }
    caption{
      font-size: 30px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>AJAX测试</h1>
  <hr>
  <button id="btn">点我加载数据</button>
  <div id="root"></div>
  <script>
    const btn = document.querySelector("#btn")
    const root = document.querySelector("#root")
    btn.onclick = () => {
      //发送请求
      fetch("http://localhost:3000/students",{
        method:"get"
      })
      .then(res => {
        
        if(res.status === 200) {
          //res.json() 读取json格式数据
          return res.json()
        } else {
          throw new Error("请求加载失败")
        }
        
      }).then(res=>{
        //获取到数据
        if(res.status == "ok") {
          const table = document.createElement("table")
          root.appendChild(table)
          table.insertAdjacentHTML("beforeend","<caption>学生列表</caption>")
          table.insertAdjacentHTML("beforeend",'<thead><tr><th>学号</th><th>姓名</th><th>年龄</th><th>地址</th></tr></thead>'
          )
          const tbody = document.createElement("tbody")
          table.appendChild(tbody)
          for(let stu of res.result) {
            table.insertAdjacentHTML("beforeend","<tr>" + "<th>" + stu.id + "</th>" +
              "<th>" + stu.name + "</th>" + "<th>" + stu.age + "</th>" + "<th>" + stu.address + "</th>" + "</tr>")
          }

        }
}).catch(err => {
        console.log("出错了",err);
      })
    }
  </script>
</body>
</html>